import React, { useState } from 'react';
import {
  Container,
  Typography,
  Box,
  Button,
  TextField,
  Alert,
  CircularProgress,
  Grid,
  Card,
  CardContent,
  Paper
} from '@mui/material';
import { useNavigate } from 'react-router-dom';
import ContentCopyIcon from '@mui/icons-material/ContentCopy';
import IconButton from '@mui/material/IconButton';

const CreditProof = ({ user }) => {
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [success, setSuccess] = useState('');
  const [proof, setProof] = useState(null);
  const [verificationCode, setVerificationCode] = useState('');

  const handleGenerateProof = async () => {
    try {
      setLoading(true);
      setError('');
      setSuccess('');
      
      const response = await fetch('http://localhost:3001/api/generate-credit-proof', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          userId: user.id,
          creditScore: user.creditScore,
        }),
      });

      const data = await response.json();
      
      if (!response.ok) {
        throw new Error(data.message || '生成信用证明失败');
      }

      setProof(data.proof);
      setVerificationCode(data.proof.verificationCode);
      setSuccess('信用证明生成成功！');
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

  const handleVerifyProof = async () => {
    try {
      setLoading(true);
      setError('');
      setSuccess('');
      
      const response = await fetch('http://localhost:3001/api/verify-credit-proof', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          proof,
          verificationCode,
        }),
      });

      const data = await response.json();
      
      if (!response.ok) {
        throw new Error(data.message || '验证信用证明失败');
      }

      setSuccess('信用证明验证成功！');
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

  const copyToClipboard = (text) => {
    navigator.clipboard.writeText(text).then(
      () => {
        setSuccess('验证码已复制到剪贴板');
      },
      () => {
        setError('复制失败，请手动复制');
      }
    );
  };

  if (!user) {
    navigate('/');
    return null;
  }

  return (
    <Container maxWidth="md" sx={{ mt: 4 }}>
      <Typography variant="h4" component="h1" gutterBottom>
        信用证明
      </Typography>

      <Grid container spacing={3}>
        <Grid item xs={12} md={6}>
          <Card>
            <CardContent>
              <Typography variant="h6" gutterBottom>
                用户信息
              </Typography>
              <Box sx={{ mb: 2 }}>
                <Typography variant="body1">
                  用户名: {user.username}
                </Typography>
                <Typography variant="body1">
                  信用分数: {user.creditScore}
                </Typography>
              </Box>
              <Button
                variant="contained"
                color="primary"
                onClick={handleGenerateProof}
                disabled={loading}
                fullWidth
              >
                {loading ? <CircularProgress size={24} /> : '生成信用证明'}
              </Button>
            </CardContent>
          </Card>
        </Grid>

        <Grid item xs={12} md={6}>
          <Card>
            <CardContent>
              <Typography variant="h6" gutterBottom>
                信用证明验证
              </Typography>
              {proof && (
                <Box sx={{ mb: 2 }}>
                  <Typography variant="body2" color="text.secondary">
                    证明ID: {proof.id}
                  </Typography>
                  <Typography variant="body2" color="text.secondary">
                    生成时间: {new Date(proof.timestamp).toLocaleString()}
                  </Typography>
                  <Paper sx={{ p: 2, mt: 2, bgcolor: 'grey.100' }}>
                    <Typography variant="subtitle2" gutterBottom>
                      验证码
                    </Typography>
                    <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                      <Typography variant="body1" sx={{ fontFamily: 'monospace' }}>
                        {verificationCode}
                      </Typography>
                      <IconButton
                        size="small"
                        onClick={() => copyToClipboard(verificationCode)}
                        title="复制验证码"
                      >
                        <ContentCopyIcon fontSize="small" />
                      </IconButton>
                    </Box>
                  </Paper>
                </Box>
              )}
              <TextField
                fullWidth
                label="验证码"
                value={verificationCode}
                onChange={(e) => setVerificationCode(e.target.value)}
                margin="normal"
                disabled={!proof}
              />
              <Button
                variant="contained"
                color="primary"
                onClick={handleVerifyProof}
                disabled={loading || !proof}
                fullWidth
                sx={{ mt: 2 }}
              >
                {loading ? <CircularProgress size={24} /> : '验证信用证明'}
              </Button>
            </CardContent>
          </Card>
        </Grid>
      </Grid>

      {error && (
        <Alert severity="error" sx={{ mt: 2 }}>
          {error}
        </Alert>
      )}
      
      {success && (
        <Alert severity="success" sx={{ mt: 2 }}>
          {success}
        </Alert>
      )}
    </Container>
  );
};

export default CreditProof; 